package com.dzl.card.service.impl;

import com.dzl.card.dao.WelfareCardTypeMapper;
import com.dzl.card.pojo.WelfareCard;
import com.dzl.card.pojo.WelfareCardPartitionRel;
import com.dzl.card.pojo.WelfareCardType;
import com.dzl.card.pojo.dto.WelfareCardTypeDto;
import com.dzl.card.pojo.query.WelfareCardTypeQuery;
import com.dzl.card.pojo.vo.WelfareCardTypeVo;
import com.dzl.card.service.WelfareCardPartitionRelService;
import com.dzl.card.service.WelfareCardService;
import com.dzl.card.service.WelfareCardTypeService;
import com.dzl.config.database.Master;
import com.dzl.config.exception.CommonException;
import com.dzl.partition.pojo.WelfarePartition;
import com.dzl.partition.service.WelfarePartitionService;
import com.dzl.util.EmptyUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 卡类型表(WelfareCardType)表服务实现类
 *
 * @author caobucao
 * @since 2021-05-18 18:51:47
 */
@Service("welfareCardTypeService")
public class WelfareCardTypeServiceImpl implements WelfareCardTypeService {

    @Autowired
    private WelfareCardTypeMapper mapper;
    @Autowired
    private WelfareCardService welfareCardService;
    @Autowired
    private WelfareCardPartitionRelService welfareCardPartitionRelService;
    @Autowired
    private WelfarePartitionService welfarePartitionService;

    @Override
    public PageInfo<WelfareCardTypeVo> selectWelfareCardTypeListPage(WelfareCardTypeQuery query) {
        PageHelper.startPage(query);
        List<WelfareCardTypeVo> list = mapper.selectWelfareCardTypeListPage(query);
        list.forEach(x -> {
            Integer cardTypeId = x.getId();
            Example example = new Example(WelfareCardPartitionRel.class);
            example.createCriteria().andEqualTo("cardTypeId", cardTypeId);
            List<WelfareCardPartitionRel> relList = welfareCardPartitionRelService.selectByExample(example);
            if(EmptyUtils.isNotEmpty(relList)) {
                List<Integer> partitionIdList = relList.stream().map(WelfareCardPartitionRel::getPartitionId).collect(Collectors.toList());
                x.setPartitionIdList(partitionIdList);
                String partitionNames = welfarePartitionService.selectByIds(partitionIdList).stream().map(WelfarePartition::getPartitionName).collect(Collectors.joining("、"));
                x.setPartitionNames(partitionNames);
            }
        });
        PageInfo<WelfareCardTypeVo> page = new PageInfo<WelfareCardTypeVo>(list);
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Master
    @Override
    public Integer saveWelfareCardType(WelfareCardTypeDto dto) {
        if (EmptyUtils.isEmpty(dto.getId())) {
            //新增
            WelfareCardType welfareCardType = new WelfareCardType();
            BeanUtils.copyProperties(dto, welfareCardType);
            List<Integer> partitionIds = dto.getPartitionIds();
            if(CollectionUtils.isEmpty(partitionIds)) {
                throw new CommonException("请选择分区！");
            }
            boolean isAllPartition = partitionIds.stream().anyMatch(x -> x.equals(0));
            //如果有全部分区
            if (isAllPartition && partitionIds.size()>1) {
                throw new CommonException("选择全部分区后不能选择其他分区！");
            }
            mapper.insertSelective(welfareCardType);
            List<WelfareCardPartitionRel> relList = new ArrayList<>();
            partitionIds.forEach(x -> {
                WelfareCardPartitionRel rel = new WelfareCardPartitionRel();
                rel.setCardTypeId(welfareCardType.getId());
                rel.setPartitionId(x);
                relList.add(rel);
            });
            //插入中间表
            welfareCardPartitionRelService.insertList(relList);
            //插入卡类型表
            return 1;
        } else {
            List<Integer> partitionIds = dto.getPartitionIds();
            if(CollectionUtils.isEmpty(partitionIds)) {
                throw new CommonException("请选择分区！");
            }
            boolean isAllPartition = partitionIds.stream().anyMatch(x -> x.equals(0));
            //如果有全部分区
            if (isAllPartition && partitionIds.size()>1) {
                throw new CommonException("选择全部分区后不能选择其他分区！");
            }
            WelfareCardType welfareCardType = new WelfareCardType();
            BeanUtils.copyProperties(dto, welfareCardType);
            //删除原中间表该卡类型的关联分区信息
            Example relExample = new Example(WelfareCardPartitionRel.class);
            relExample.createCriteria().andEqualTo("cardTypeId", dto.getId());
            welfareCardPartitionRelService.deleteByExample(relExample);
            //更新数据
            mapper.updateByPrimaryKeySelective(welfareCardType);
            //给中间表插入数据
            List<WelfareCardPartitionRel> relList = new ArrayList<>();
            partitionIds.forEach(x -> {
                WelfareCardPartitionRel rel = new WelfareCardPartitionRel();
                rel.setCardTypeId(welfareCardType.getId());
                rel.setPartitionId(x);
                relList.add(rel);
            });
            //插入中间表
            welfareCardPartitionRelService.insertList(relList);
            return 1;
        }
    }

    @Override
    public List<Integer> selectPartitionIdByCardTypeId(Integer cardTypeId) {
        return mapper.selectPartitionIdByCardTypeId(cardTypeId);
    }

    @Override
    public Integer deleteCardType(Integer id) {
        //查询该卡关联的卡总数
        Example countRelateCardExample = new Example(WelfareCard.class);
        countRelateCardExample.createCriteria().andEqualTo("cardTypeId", id).andEqualTo("status", 1);
        int countRelateCard = welfareCardService.selectCountByExample(countRelateCardExample);
        if(countRelateCard > 0) {
            throw new CommonException("该卡类型已关联卡，无法删除");
        }
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Integer selectShowClassifyEntryByUserId(Integer userId) {
        return mapper.selectShowClassifyEntryByUserId(userId);
    }
}
